package com.gali.leetcode.day12;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Auther: gali
 * @Date: 2022-07-27 18:11
 * @Description:
 */
public class Solution {
    /**
     * 组合总数--回溯(可以重复)
     * @param candidates
     * @param target
     * @return
     */
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> list = new ArrayList<>();
        List<Integer> item = new ArrayList<>();
        Arrays.sort(candidates);
        dfs(candidates,target,item,list,0);
        return list;
    }

    private void dfs(int[] candidates, int target, List<Integer> item, List<List<Integer>> list,Integer index) {
        if (index==candidates.length){
            return;
        }
        if (target==0){
            list.add(new ArrayList<>(item));
            return;
        }
        dfs(candidates,target,item,list,index+1);
        if (target-candidates[index]<0) return;
            item.add(candidates[index]);
            dfs(candidates,target-candidates[index],item,list,index);
            item.remove(item.size()-1);  //回溯到上一步
    }

    /**
     * 组合总数-不可以重复(问题：两个长度的不行)
     * @param candidates
     * @param target
     * @return
     */
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> list = new ArrayList<>();
        List<Integer> item = new ArrayList<>();
        Arrays.sort(candidates);
        dfs2(candidates,target,item,list,0);
        return list;
    }

    private void dfs2(int[] candidates, int target, List<Integer> item, List<List<Integer>> list, int index) {
        if (index==candidates.length){
            return;
        }
        if (target==candidates[index]&&item.size()==0){
            item.add(candidates[index]);
            list.add(new ArrayList<>(item));
            item.remove(item.size()-1);
            return;
        }
        if (target==0){
            //去重
            if (list.contains(item)){
                return;
            }
            list.add(new ArrayList<>(item));
            return;
        }
        dfs2(candidates,target,item,list,index+1);
        if (target-candidates[index]<0) return;
        if (target-candidates[index]>=0){
            item.add(candidates[index]);
            dfs2(candidates,target-candidates[index],item,list,index+1);
            if (item.get(index)!=item.get(index+1))
            item.remove(item.size()-1);  //回溯到上一步
        }
    }
}
